<?php
/**
* @copyright Copyright (C) 2008 Cory Webb. All rights reserved.
* @license GNU/GPL
*
* Special thanks to Simon Tiplady (http://www.stiplady.net) for help with the regular expressions.
* Updated June 4th, 2010 - (http://www.STiplady.net/Joomla) Added support for additional url formats, and converted to the swfobject method
*/

// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
* YouTube Video Embedder Content Plugin
*
*/
class plgContentYoutubeEmbed extends JPlugin
{

	/**
	* Constructor
	*
	* @param object $subject The object to observe
	* @param object $params The object that holds the plugin parameters
	*/
	function plgContentYoutubeEmbed( &$subject, $params )
	{
		parent::__construct( $subject, $params );
	}

	/**
	* Example prepare content method
	*
	* Method is called by the view
	*
	* @param object The article object. Note $article->text is also available
	* @param object The article params
	* @param int The 'page' number
	*/
	function onPrepareContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
	
		if ( JString::strpos( $article->text, 'http://www.youtube.com/' ) === false ) {
			return true;
		}
		/**
		 * matches the follwing url formats
		 * http://www.youtube.com/user/username#p/a/u/1/abcdefghijk
		 * http://www.youtube.com/username#p/a/u/1/abcdefghijk
		 * http://www.youtube.com/watch?v=abcdefghijk
		 */
		$article->text = preg_replace('@(http://www.youtube.com/(?:watch\?v=|(?:user/)?[^#]+#p/a/u/[0-9]+/)([a-zA-Z0-9_-]+))@e', '$this->youtubeCodeEmbed("\2")', $article->text);
	
		return true;
	
	}

	function youtubeCodeEmbed( $vCode )
	{
		static $isSWFLoaded = FALSE;

		$document =& JFactory::getDocument();

		if ( !$isSWFLoaded ) {
			$document->addScript('http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js');
			$isSWFLoaded = TRUE;
		}

		$plugin =& JPluginHelper::getPlugin('content', 'youtubeembed');
	 	$params = new JParameter( $plugin->params );

		$width = $params->get('width', 425);
		$height = $params->get('height', 344);

		$js = <<< EOS
		var params = { allowScriptAccess: "always" };
		var atts = { id: "myytplayer_$vCode" };
		swfobject.embedSWF("http://www.youtube.com/v/$vCode", "ytapiplayer_$vCode", "$width", "$height", "8", null, null, params, atts);
EOS;
		$document->addScriptDeclaration($js);
	
		return '<div id="ytapiplayer_'.$vCode.'">You need Flash player 8+ and JavaScript enabled to view this video.</div>';
	}

}
